package com.share.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Test2Interceptor implements HandlerInterceptor {
    /*
    1、返回值：是否将当前的请求拦截下俩，如果返回false，请求将被终止
    2、参数Object：表示被拦截请求的目标
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("####pre");
        System.out.println("###请求路径：" + request.getRequestURI());
        request.setCharacterEncoding("utf-8");
        //如果是登录页面则放行
        if(request.getRequestURI().indexOf("login")>=0){
            return true;
        }
//        HttpSession session = request.getSession();
//        //如果用户已登录也放行
//        if(session.getAttribute("username")!=null){
//            return true;
//        }
//        //用户没有登录挑战到登录页面
//        request.getRequestDispatcher("login").forward(request, response);
//        return false;

        return true;

    }

    /*
   1、参数ModelAndView：可以通过该参数改变显示的视图，或修改发往视图的方法
    */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("####post");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("####after");
    }
}
